package com.yunshipei.ui.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yunshipei.adapter.SSOSettingAdapter;
import com.yunshipei.common.Globals;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.core.utils.CommonUtils;
import com.yunshipei.db.green.XCloudSign;
import com.yunshipei.db.green.XCloudSignDao;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.EnterDbManager;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.SSOSModel;
import com.yunshipei.model.SSOSettingModel;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.activity.SSOSettingDetailActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import io.rong.eventbus.EventBus;

public class SWAFragment extends BaseBodyFragment {

    public static int SSO_REQUEST_CODE = 301;

    private List<SSOSettingModel> mSsoSettingModels = new ArrayList<>();
    private SSOSettingAdapter mSsoSettingAdapter;

    @Bind(R.id.et_title_bar)
    protected YspTitleBar mTitleBar;
    @Bind(R.id.list_sso_settings)
    protected ListView mListView;

    public static SWAFragment newInstance(MainExtraBean mainExtraBean) {
        SWAFragment swaFragment = new SWAFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_CUSTOMER_MAIN_DATA, mainExtraBean);
        swaFragment.setArguments(bundle);
        return swaFragment;
    }

    @Override
    public int viewLayout() {
        return R.layout.fragment_swa;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        mTitleBar.setTitle(getString(R.string.sso_login_setting_title));
        if (isPad()) {
            mTitleBar.setBackClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EventBus.getDefault().post(new YspEvent.PadClick(SettingsFragment.class.getName()));
                }
            });
        }
        initData();
        initView();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private void initView() {
        if (mSsoSettingModels.size() == 0) return;
        if (mSsoSettingAdapter == null) {
            View header = View.inflate(mContext, R.layout.tv_sso_message, null);
            header.setOnClickListener(null);
            mListView.addHeaderView(header);
            mSsoSettingAdapter = new SSOSettingAdapter(mContext, mSsoSettingModels);
            mListView.setAdapter(mSsoSettingAdapter);
        } else {
            mSsoSettingAdapter.notifyDataSetChanged();
        }
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SSOSettingModel ssoSettingModel = mSsoSettingModels.get(position - 1);
                if (!ssoSettingModel.isUnity()) {
                    if (isPad()) {
                        EventBus.getDefault().post(new YspEvent.SWASetting(ssoSettingModel));
                    } else {
                        Intent intent = new SSOSettingDetailActivity.SSOSettingDetailIntentBuilder(mContext).setSSOModel(ssoSettingModel).setMainExtra(mMainExtraBean).getIntent();
                        startActivityForResult(intent, SSO_REQUEST_CODE);
                    }
                }
            }
        });
    }

    private void initData() {
        String sso = YspPreferences.getInstance().getSharedPreferences().getString(Globals.YSP_SSO_OBJECT, "");
        if (!TextUtils.isEmpty(sso)) {
            List<SSOSModel> ssoModels = new Gson().fromJson(sso, new TypeToken<List<SSOSModel>>() {
            }.getType());
            if (ssoModels != null) {
                XCloudSignDao dao = EnterDbManager.getInstances().getXCloudSignDao();
                for (SSOSModel ssosModel : ssoModels) {
                    String host = CommonUtils.getHost(ssosModel.address);
                    if (!TextUtils.isEmpty(host)) {
                        XCloudSign xCloudSign = null;
                        try {
                            xCloudSign = dao.queryBuilder().where(XCloudSignDao.Properties.Host.eq(host)).build().unique();
                        } catch (Exception ignored) {
                        }
                        SSOSettingModel ssoSettingModel = new SSOSettingModel();
                        String userLoginType = ssosModel.userLoginType;
                        boolean isUnity = !TextUtils.isEmpty(userLoginType) && "Unify".equalsIgnoreCase(userLoginType);
                        ssoSettingModel.setUnity(isUnity);
                        ssoSettingModel.setUrl(ssosModel.address);
                        ssoSettingModel.setHost(host);
                        ssoSettingModel.setName(ssosModel.systemName);
                        ssoSettingModel.setAvailable(xCloudSign != null);
                        ssoSettingModel.setImgUrl(ssosModel.imgUrl);
                        ssoSettingModel.setType(ssosModel.type);
                        mSsoSettingModels.add(ssoSettingModel);
                    }
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        if (requestCode == SSO_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            String host = data.getStringExtra(SWADetailFragment.EXTRA_RESULT_DATA);
            swaSettingChanged(host);
        }
    }

    public void onEventMainThread(YspEvent.SWASettingChange swaSettingChange) {
        swaSettingChanged(swaSettingChange.host);
    }

    private void swaSettingChanged(String host) {
        if (!TextUtils.isEmpty(host)) {
            for (SSOSettingModel ssoSettingModel : mSsoSettingModels) {
                if (ssoSettingModel.getHost().equals(host)) {
                    ssoSettingModel.setAvailable(true);
                    mSsoSettingAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }
}
